package com.ptadmin.report;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ptadmin.report.executor.GetReportsExecutor;
import com.ptadmin.report.executor.ProcessReportsExecutor;
import com.ptadmin.report.executor.RequestReportExecutor;

public class ReportApplication {
	private static Options options = new Options();
	private static final Logger logger = LoggerFactory.getLogger(ReportApplication.class);
	
	// report type reference: http://docs.developer.amazonservices.com/en_US/reports/Reports_ReportType.html
	
	// _GET_FLAT_FILE_OPEN_LISTINGS_DATA_ : Tab-delimited flat file open listings report that contains a summary of the seller's product listings with the price and quantity for each SKU. For Marketplace and Seller Central sellers.
	// _GET_MERCHANT_LISTINGS_ALL_DATA_ : Tab-delimited flat file detailed all listings report. For Marketplace and Seller Central sellers.
	// _GET_XML_BROWSE_TREE_DATA_ : XML report that provides browse tree hierarchy information and node refinement information for the Amazon retail website in any marketplace. Can be requested or scheduled. For Marketplace and Seller Central sellers.
	
	private static String[] argsInput = {
//			"-m", "A2N95VZZXMVRLW", 
//			"-a", "A2N95VZZXMVRLW;amzn.mws.52b2d181-1d65-65a8-04f7-e12ce26cfad5",
			"-a", "A3C79HMK4O8JLQ;amzn.mws.c2b85f88-d34d-735b-6964-ac1d5f14086e",
			"-r",
			"-m", "ATVPDKIKX0DER",
			"-t", "_GET_XML_BROWSE_TREE_DATA_",
//			"-t", "_GET_FLAT_FILE_OPEN_LISTINGS_DATA_",
//			"-t", "_GET_MERCHANT_LISTINGS_ALL_DATA_",
//			"-r", "ATVPDKIKX0DE2",
//			"-t", "inventory", 
//			"-n", "1", 
			"-s", "2011-01-01", 
			"-p", "1",
			"-e", "<RequestReportId>",
			"-o", "BrowseTreeNode_30726983172018784_Xml"
			};
	
	public static void main(String... args) {
		
		args = argsInput;
		
		options.addOption("h", "help", false, "show help.");
		options.addOption("a", "sellerAndTokenPair", true, "input merchantId(sellerId) sellerDevAuthToken pair (<a>;<b> as separator)");

		options.addOption("r", "request-report", false, "start to request report");
		options.addOption("m", "marketplaces", true, "input marketplaces(xxxxx,xxxxx)");
		options.addOption("t", "report-type", true, "report type, input h for help");
//		options.addOption("n", "report-name", true, "report name, input h for help");
		options.addOption("s", "start-date", true, "start date of report");
		options.addOption("p", "period", true, "period days of report");

		options.addOption("e", "get-report", true, "start to download report, specify the request report Id to download");
		options.addOption("o", "process-report", true, "process downloaded report only, and specify the downloaded report file as value");

		CommandLineParser parser = new DefaultParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String sellerId = "";
		String sellerDevAuthToken = "";
		List<String> requestReportIdList = new ArrayList<String>();

		// Step1: Request report
		if (cmd.hasOption("r")) {
			RequestReportExecutor.Builder builder = new RequestReportExecutor.Builder();
			if (cmd.hasOption("a")) {
				String[] sellerAndTokenPair = cmd.getOptionValue("a").split(";");
				sellerId = sellerAndTokenPair[0];
				sellerDevAuthToken = sellerAndTokenPair[1];
				builder.with(sellerId, sellerDevAuthToken);
			} else {
				System.out.println("require sellerAndTokenPair...");
				System.exit(0);
			}

			if (cmd.hasOption("m")) {
				String[] marketplaceIdArray = cmd.getOptionValues("r");
				for(String marketplaceId : marketplaceIdArray) {
					builder.withMarketplaceId(marketplaceId);
				}
			} else {
				System.out.println("require at least one marketplace...");
				System.exit(0);
			}

			if (cmd.hasOption("t")) {
				String[] reportTypeArray = cmd.getOptionValues("t");
				for(String reportType : reportTypeArray) {
					builder.withReportType(reportType);
				}
			} else {
				System.out.println("require at least one reporttype...");
				System.exit(0);
			}

			if (cmd.hasOption("s") && cmd.hasOption("p")) {
				LocalDate startDate = LocalDate.parse(cmd.getOptionValue("s"));
				long period = Long.parseLong(cmd.getOptionValue("p"));
				builder.withStartDate(startDate, period);
			} else {
				System.out.println("required startDate and period...");
				System.exit(0);
			}

			RequestReportExecutor rre = builder.build();
			requestReportIdList = rre.execute();

			logger.info(">>>>>>>>> request report is submitted...");

			try {
				logger.info(">>>>>>>>> sleeping...");
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		// Step2: Get report from Amazon
		if (cmd.hasOption("e")) {
			requestReportIdList =  Arrays.asList(cmd.getOptionValue("e").split(","));
		}
		List<String> reportFilePathList;
		GetReportsExecutor.Builder builder2 = new GetReportsExecutor.Builder();
		builder2.with(sellerId, sellerDevAuthToken);
		for (String reportRequestId : requestReportIdList) {
			builder2.withReportRequestId(reportRequestId);
		}
		reportFilePathList = builder2.build().execute();

		// Step3: Post process report -> convert to json & save to mongodb
		if (cmd.hasOption("o")) {
			reportFilePathList =  Arrays.asList(cmd.getOptionValue("o").split(","));
		}
		ProcessReportsExecutor.Builder builder3 = new ProcessReportsExecutor.Builder();
		for(String reportFilePath : reportFilePathList) {
			builder3.withReportName("browseTreeNode");
			builder3.withMerchantId("mock_noneed");
			builder3.withReportFilePath(reportFilePath);
		}
		builder3.build().execute();



//
//
//		String[] startFromRequestReportIds = null;
//		if (cmd.hasOption("e")) {
//			startFromRequestReportIds = cmd.getOptionValue("e").split(",");
//
//
//			reportFilePathList = builder2.build().execute();
//		}
//
//		String startFromProcessReportFilePath = "";
//		if (cmd.hasOption("o")) {
//			reportFilePathList = new String[1]()
//			startFromProcessReportFilePath = cmd.getOptionValue("o");
//			// Post process report -> convert to json & save to mongodb
//			ProcessReportsExecutor.Builder builder3 = new ProcessReportsExecutor.Builder();
//			for(String reportFilePath : reportFilePathList) {
//				builder3.withReportName("browseTreeNode");
//				builder3.withMerchantId("mock_noneed");
//				builder3.withReportFilePath(reportFilePath);
//			}
//			builder3.build().execute();
//		}
//
////		boolean startFromProcessReport = false;
////		String startFromProcessReportFilePath = "";
////		if (cmd.hasOption("o")) {
////			startFromProcessReport = true;
////			startFromProcessReportFilePath = cmd.getOptionValue("o");
////		}
//
//		// Start execution
//		List<String> reportFilePathList;
//		if (!startFromProcessReport) {
////			RequestReportExecutor rre = builder.build();
////			List<String> requestReportIdList = rre.execute();
////
////			logger.info(">>>>>>>>> request report is submitted...");
////
////			try {
////				logger.info(">>>>>>>>> sleeping...");
////				Thread.sleep(30000);
////			} catch (InterruptedException e) {
////				e.printStackTrace();
////			}
//
//			// mock data ==>
////		String sellerId = "A2N95VZZXMVRLW";
////		String sellerDevAuthToken = "amzn.mws.52b2d181-1d65-65a8-04f7-e12ce26cfad5";
////		List<String> requestReportIdList = new ArrayList<String>();
////		requestReportIdList.add("50079017887");
////		requestReportIdList.add("50080017887");
//			// <==
//
////			// Get report from Amazon
////			GetReportsExecutor.Builder builder2 = new GetReportsExecutor.Builder();
////			builder2.with(sellerId, sellerDevAuthToken);
////			for (String reportRequestId : requestReportIdList) {
////				builder2.withReportRequestId(reportRequestId);
////			}
////
////			reportFilePathList = builder2.build().execute();
//		} else {
//			reportFilePathList = new ArrayList<String>();
//			reportFilePathList.add(startFromProcessReportFilePath);
//		}
//
//		// Post process report -> convert to json & save to mongodb
//		ProcessReportsExecutor.Builder builder3 = new ProcessReportsExecutor.Builder();
//		for(String reportFilePath : reportFilePathList) {
//			builder3.withReportName("browseTreeNode");
//			builder3.withMerchantId("mock_noneed");
//			builder3.withReportFilePath(reportFilePath);
//		}
//		builder3.build().execute();
	}
}
